package com.coolingme.general.transparent;

import java.util.ArrayList;
import java.util.List;

/**
 * 树枝节点,拥有添加删除子节点和查询子节点的功能
 *
 * @author wangyue
 * @date 2020-09-18 23:30
 */
public class Composite extends Component {

    /**
     * 存放子节点的容器
     */
    private List<Component> itemList;

    public Composite(String name) {
        super(name);
        this.itemList = new ArrayList<>();
    }

    @Override
    public String operation() {
        StringBuilder result = new StringBuilder(name);
        for (Component component : itemList) {
            result.append("\n");
            // 递归
            result.append(component.operation());
        }
        return result.toString();
    }

    @Override
    public boolean addChild(Component component) {
        return itemList.add(component);
    }

    @Override
    public boolean removeChild(Component component) {
        return itemList.remove(component);
    }

    @Override
    public Component getChild(Integer index) {
        return itemList.get(index);
    }
}
